package com.mmg.cosplay.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.mmg.cosplay.entity.R;
import com.mmg.cosplay.entity.User;
import com.mmg.cosplay.entity.dto.LoginRequest;
import com.mmg.cosplay.entity.dto.LoginResponse;
import com.mmg.cosplay.entity.dto.UserDto;
import com.mmg.cosplay.service.UserService;
import com.mmg.cosplay.utils.CaptchaUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户认证相关接口")
@RestController
@RequestMapping("/user")
public class AuthController {

    @Autowired
    private UserService userService;

    @Resource
    private CaptchaUtil captchaUtil;

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public ResponseEntity login(@Valid @RequestBody LoginRequest request) {
        try {
            // 检查验证码是否已通过验证
            if (!captchaUtil.checkCaptchaVerified()) {
                return R.error("请先完成滑块验证");
            }
            // 验证通过后清除验证结果，防止重复使用
            captchaUtil.clearCaptchaResult();
            LoginResponse response = userService.login(request);
            return R.success("登录成功", response);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public ResponseEntity register(@Valid @RequestBody User user) {
        try {
            // 检查验证码是否已通过验证
            if (!captchaUtil.checkCaptchaVerified()) {
                return R.error("请先完成滑块验证");
            }
            // 验证通过后清除验证结果，防止重复使用
            captchaUtil.clearCaptchaResult();
            User existingUser = userService.getAccountByUsername(user.getUsername());
            if (existingUser != null) {
                return R.error("用户名已存在");
            }
            Boolean flag = userService.saveUser(user);
            if (flag) {
                return R.success("注册成功");
            } else {
                return R.error("注册失败");
            }
        } catch (Exception e) {
            return R.error("注册失败");
        }
    }

    /**
     * 用户信息修改
     */
    @Operation(summary = "用户信息修改")
    @PutMapping("/update")
    public ResponseEntity updateUser(@Valid @RequestBody UserDto userDto) {
        try {
            User user = new User();
            Long loginId = StpUtil.getLoginIdAsLong();
            user.setId(loginId);
            BeanUtils.copyProperties(userDto, user);
            Boolean flag = userService.updateUser(user);
            if (flag) {
                StpUtil.logout();
            }
            return R.success("用户信息更新成功");
        } catch (Exception e) {
            return R.error("用户信息更新失败: " + e.getMessage());
        }
    }

    /**
     * 用户退出登录
     */
    @Operation(summary = "用户退出登录")
    @PostMapping("/logout")
    public ResponseEntity logout() {
        StpUtil.logout();
        return R.success("退出登录成功");
    }

    /**
     * 获取当前登录用户的信息
     */
    @Operation(summary = "获取当前登录用户的信息")
    @GetMapping("/info")
    public ResponseEntity getUserInfo() {
        try {
            Object loginId = StpUtil.getLoginId();
            return R.success("获取用户信息成功", loginId);
        } catch (Exception e) {
            return R.error("未登录");
        }
    }
}
